package com.yfeng.goodjuhome.service.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;




import com.yfeng.common.dao.IDao;
import com.yfeng.common.dao.Param;
import com.yfeng.common.utils.BeanUtil;

import com.yfeng.goodjuhome.model.Group;
import com.yfeng.goodjuhome.service.IGroupService;

@Service("groupService")
public class GroupServiceImpl implements IGroupService {

	private final Log log = LogFactory.getLog(this.getClass());
	@Autowired
	public IDao baseDao;
	Group group = null;
	
	/*
	 * 添加用户
	 * @see com.bw.callcenter.sys.service.IUserService#addUser(com.bw.callcenter.sys.model.User, com.bw.callcenter.sys.model.UserGroup, java.lang.String)
	 */

	public int addGroup(String name,String groupid,String userid)  throws Exception{

		Group group = (Group)BeanUtil.getBean("group");
		if (group.isExist(name))
			return -1;

		Param param = new Param();
		param.put("name", name);
		param.put("pid", groupid);
		param.put("uid", userid);
		int pk = baseDao.save("groups", param);
		if (pk > 0) {
			return 1;
		}
		return 0;

	}
	
	/*
	 * 修改用户
	 * @see com.bw.callcenter.sys.service.IUserService#modUser(com.bw.callcenter.sys.model.User, com.bw.callcenter.sys.model.UserGroup, java.lang.String)
	 */

	public int modGroup(String uid,String name,String groupid)  throws Exception{
	
		Param param = new Param();
		int ret=baseDao.getRowCount("from groups where id!="+uid+" and name=:name", new Param("name", name));
		if(ret>0)
			return -1;
		param.put("name", name, Param.VALUE);
		param.put("pid", groupid,Param.VALUE);
		param.put("id", uid, Param.CONDITION);
		int pk = baseDao.save("groups", param);
		return pk;

	}
	

	public Group getGroup() {
		return group;
	}

	/**
	 * 删除用户
	 */
	public int deleteGroup(String[] ids) throws Exception {

		try {
			Group group = (Group)BeanUtil.getBean("group");

			for (int i = 0; i < ids.length; i++) {
				int ret=baseDao.getRowCount("from users where groupid=:groupid",new Param("groupid",ids[i]));
				if(ret>0){
					return -1;
				}else{
					int ret2=baseDao.getRowCount("from groups where pid=:pid",new Param("pid",ids[i]));
					if(ret2>0){
						return -2;
					}
				}
				baseDao.delete("groups", new Param("id", ids[i]));
			}
			return 1;
		} catch (Exception e) {
			log.error(e);

		}
		return 0;

	}
	
	

}
